package car_test;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class mr_gender_analysis {

    public static class MyMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        private final static IntWritable one = new IntWritable(1);
        private Text genderKey = new Text();

        @Override
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            // 将输入的文本按GBK编码转换为字符串，以处理中文字符
            String line = new String(value.getBytes(), 0, value.getLength(), "GBK");
            // 使用正则表达式分割字符串，同时考虑逗号和引号的情况
            String[] strs = line.trim().split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);

            // 确保数据完整性
            if (strs != null && strs.length == 39) {
                // 获取第39列的性别字段
                String gender = strs[38].trim();

                // 仅统计“女性”和“男性”
                if ("女性".equals(gender)) {
                    genderKey.set("female");
                    context.write(genderKey, one);
                } else if ("男性".equals(gender)) {
                    genderKey.set("male");
                    context.write(genderKey, one);
                }
            }
        }
    }

    public static class MyReducer extends Reducer<Text, IntWritable, Text, DoubleWritable> {
        private Map<String, Long> counts = new HashMap<>();
        private long total = 0;

        @Override
        public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }

            // 存储每个性别的数量并更新总数
            counts.put(key.toString(), sum);
            total += sum;
        }

        @Override
        public void cleanup(Context context) throws IOException, InterruptedException {
            // 计算比例并输出结果
            for (Map.Entry<String, Long> entry : counts.entrySet()) {
                double ratio = (double) entry.getValue() / total;
                context.write(new Text(entry.getKey()), new DoubleWritable(ratio));
            }
        }
    }

    public static void main(String[] args) throws Exception {
        // 设置NameNode的IP地址
        String namenode_ip = "192.168.128.130";
        // 构建HDFS的URL
        String hdfs = "hdfs://" + namenode_ip + ":8020";

        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", hdfs);

        Job job = Job.getInstance(conf, "gender analysis");

        job.setJarByClass(mr_gender_analysis.class);
        job.setMapperClass(MyMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setReducerClass(MyReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(DoubleWritable.class);

        String dataDir = "/car/data.csv";
        String outputDir = "/Output/gender_analysis";

        Path inPath = new Path(hdfs + dataDir);
        Path outPath = new Path(hdfs + outputDir);

        FileInputFormat.addInputPath(job, inPath);
        FileOutputFormat.setOutputPath(job, outPath);

        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(outPath)) {
            fs.delete(outPath, true);
        }

        System.out.println("Job: gender analysis is running...");
        boolean success = job.waitForCompletion(true);
        if (success) {
            System.out.println("Job succeeded!");
        } else {
            System.out.println("Job failed!");
            System.exit(1);
        }
    }
}
